home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1994 June: Reference Library / Dev.CD Jun 94.toast / Periodicals / develop / develop Issue 9 / develop 9 code / TermWindow / SampleTermWindow.c < prev    next >
Encoding:
C/C++ Source or Header  |  1992-01-06  |  33.4 KB  |  1,025 lines  |  [TEXT/MPS ]

  1. /******************************************************************************
  2. **
  3. **  Project Name:    SampleTermWindow
  4. **     File Name:    SampleTermWindow.c
  5. **
  6. **   Description:    Our main code for this applications.  Based almost entirely
  7. **                    off the DTS 'Sample' "{cexamples}" application.
  8. **
  9. **                       Copyright © 1988-1991 Apple Computer, Inc.
  10. **                       All rights reserved.
  11. **
  12. *******************************************************************************
  13. **                       A U T H O R   I D E N T I T Y
  14. *******************************************************************************
  15. **
  16. **    Initials    Name
  17. **    --------    -----------------------------------------------
  18. **    CSH            Craig Hotchkiss
  19. **
  20. *******************************************************************************
  21. **                      R E V I S I O N   H I S T O R Y
  22. *******************************************************************************
  23. **
  24.     Change History (most recent first):
  25. **
  26. ******************************************************************************/
  27.  
  28.  
  29. #ifdef DUMPFILENAME
  30.     #pragma load DUMPFILENAME
  31. #else
  32.     #include <Values.h>
  33.     #include <Types.h>
  34.     #include <Resources.h>
  35.     #include <QuickDraw.h>
  36.     #include <Fonts.h>
  37.     #include <Events.h>
  38.     #include <Windows.h>
  39.     #include <Menus.h>
  40.     #include <TextEdit.h>
  41.     #include <Dialogs.h>
  42.     #include <Desk.h>
  43.     #include <ToolUtils.h>
  44.     #include <Memory.h>
  45.     #include <SegLoad.h>
  46.     #include <Files.h>
  47.     #include <OSUtils.h>
  48.     #include <OSEvents.h>
  49.     #include <DiskInit.h>
  50.     #include <Packages.h>
  51.     #include <Traps.h>
  52.  
  53.     //these are specific to TermWindow
  54.     #include     <CommResources.h>
  55.     #include     <CTBUtilities.h>
  56.     #include     <GestaltEqu.h>
  57.     #include     <Terminals.h>
  58. #endif
  59.  
  60.  
  61.  
  62. #ifndef __SAMPLETERMWINDOW__
  63.     #include "SampleTermWindow.h"
  64. #endif
  65.  
  66. #ifndef __TERMWINDOW__
  67.     #include "TermWindow.h"
  68. #endif
  69.  
  70.  
  71.  
  72. /********************************************************************************
  73. *                                    Typedefs
  74. ********************************************************************************/
  75. struct AppWindowRec
  76. {
  77.     WindowRecord                fWindowRec;            // so it can be a WindowPtr
  78.     short                        fWindowType;        // for application usage
  79. };
  80. typedef    struct AppWindowRec AppWindowRec;
  81. typedef    AppWindowRec *AppWindowPtr;
  82.  
  83.  
  84.  
  85. /********************************************************************************
  86. *                                Other constants
  87. ********************************************************************************/
  88.     // types our application understands
  89. #define    kNILWINDOW                    0
  90. #define    kUNKNOWNWINDOW                1
  91. #define    kDAWINDOW                    2
  92.  
  93. #define kAPPWINDOW                    3
  94. #define kDEBUGWINDOW                99
  95.  
  96.  
  97.  
  98. /* The "g" prefix is used to emphasize that a variable is global. */
  99.  
  100. /* GMac is used to hold the result of a SysEnvirons call. This makes
  101.    it convenient for any routine to check the environment. */
  102. SysEnvRec    gMac;                /* set up by Initialize */
  103.  
  104. /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  105.    trap is available. If it is false, we know that we must call GetNextEvent. */
  106. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  107.  
  108. /* GInBackground is maintained by our osEvent handling routines. Any part of
  109.    the program can check it to find out if it is currently in the background. */
  110. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  111.  
  112.  
  113. /* The following globals are the state of the window. If we supported more than
  114.    one window, they would be attatched to each document, rather than globals. */
  115.  
  116. /* GStopped tells whether the stop light is currently on stop or go. */
  117. Boolean        gStopped;            /* maintained by Initialize and SetLight */
  118.  
  119. /* GStopRect and gGoRect are the rectangles of the two stop lights in the window. */
  120. Rect        gStopRect;            /* set up by Initialize */
  121. Rect        gGoRect;            /* set up by Initialize */
  122.  
  123. //
  124. //Common TermWindowRec -- for TermWindow
  125. //
  126.     TermWindowPtr        gTermWindowPtr;
  127.  
  128.  
  129. /* Here are declarations for all of the C routines. In MPW 3.0 we can use
  130.    actual prototypes for parameter type checking. */
  131. void EventLoop( void );
  132. void DoEvent( EventRecord *event );
  133. pascal short WindowType(WindowPtr theWindowPtr);
  134. void AdjustCursor( Point mouse, RgnHandle region );
  135. void GetGlobalMouse( Point *mouse );
  136. void DoUpdate( WindowPtr window );
  137. void DoActivate( WindowPtr window, Boolean becomingActive );
  138. void DoContentClick( WindowPtr window );
  139. void DrawWindow( WindowPtr window );
  140. void AdjustMenus( void );
  141. void DoMenuCommand( long menuResult );
  142. void SetLight( WindowPtr window, Boolean newStopped );
  143. Boolean DoCloseWindow( WindowPtr window );
  144. void Terminate( void );
  145. void Initialize( void );
  146. Boolean GoGetRect( short rectID, Rect *theRect );
  147. void ForceEnvirons( void );
  148. Boolean IsAppWindow(WindowPtr window);
  149. Boolean IsDAWindow( WindowPtr window );
  150. Boolean TrapAvailable( short tNumber, TrapType tType );
  151. void AlertUser( void );
  152.  
  153.  
  154. /* Define HiWrd and LoWrd macros for efficiency. */
  155. #define HiWrd(aLong)    (((aLong) >> 16) & 0xFFFF)
  156. #define LoWrd(aLong)    ((aLong) & 0xFFFF)
  157.  
  158. /* Define TopLeft and BotRight macros for convenience. Notice the implicit
  159.    dependency on the ordering of fields within a Rect */
  160. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  161. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  162.  
  163. #ifndef THINK_C
  164.     extern void _DataInit();
  165. #endif
  166.  
  167. /* This routine is part of the MPW runtime library. This external
  168.    reference to it is done so that we can unload its segment, %A5Init. */
  169.  
  170.  
  171. #pragma segment Main
  172. main()
  173. {
  174. #ifndef THINK_C
  175.     UnloadSeg((Ptr) _DataInit);        /* note that _DataInit must not be in Main! */
  176. #endif
  177.     
  178.     /* 1.01 - call to ForceEnvirons removed */
  179.     
  180.     /*    If you have stack requirements that differ from the default,
  181.         then you could use SetApplLimit to increase StackSpace at 
  182.         this point, before calling MaxApplZone. */
  183.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  184.  
  185.     Initialize();                    /* initialize the program */
  186.  
  187. #ifndef THINK_C
  188.     UnloadSeg((Ptr) Initialize);    /* note that Initialize must not be in Main! */
  189. #endif
  190.  
  191.     EventLoop();                    /* call the main event loop */
  192. }
  193.  
  194.  
  195. /*    Get events forever, and handle them by calling DoEvent.
  196.     Get the events by calling WaitNextEvent, if it's available, otherwise
  197.     by calling GetNextEvent. Also call AdjustCursor each time through the loop. */
  198.  
  199. #pragma segment Main
  200. void EventLoop()
  201. {
  202.     RgnHandle    cursorRgn;
  203.     Boolean        gotEvent;
  204.     EventRecord    event;
  205.     Point        mouse;
  206.  
  207.  
  208.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  209.     do {
  210.         /* use WNE if it is available */
  211.         if ( gHasWaitNextEvent ) {
  212.             GetGlobalMouse(&mouse);
  213.             AdjustCursor(mouse, cursorRgn);
  214.             gotEvent = WaitNextEvent(everyEvent, &event, MAXLONG, cursorRgn);
  215.         }
  216.         else {
  217.             SystemTask();
  218.             gotEvent = GetNextEvent(everyEvent, &event);
  219.         }
  220.             //
  221.             //    These are the dispatchers for the TermWindow stuff.
  222.             //
  223.         if (IsTermWindowEvent(gTermWindowPtr, &event)) {
  224.             HandleTermWindowEvent(gTermWindowPtr, &event);
  225.             gotEvent = false;
  226.         }
  227.         
  228.         if ( gotEvent ) {
  229.             /* make sure we have the right cursor before handling the event */
  230.             AdjustCursor(event.where, cursorRgn);
  231.             DoEvent(&event);
  232.         }
  233.         /*    If you are using modeless dialogs that have editText items,
  234.             you will want to call IsDialogEvent to give the caret a chance
  235.             to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  236.             for a non-NIL value before calling IsDialogEvent. */
  237.     } while ( true );    /* loop forever; we quit via ExitToShell */
  238. } /*EventLoop*/
  239.  
  240.  
  241. /* Do the right thing for an event. Determine what kind of event it is, and call
  242.  the appropriate routines. */
  243.  
  244. #pragma segment Main
  245. void DoEvent(event)
  246.     EventRecord    *event;
  247. {
  248.     short        part, err;
  249.     WindowPtr    window;
  250.     Boolean        hit;
  251.     char        key;
  252.     Point        aPoint;
  253.  
  254.     switch ( event->what ) {
  255.         case mouseDown:
  256.             part = FindWindow(event->where, &window);
  257.             switch ( part ) {
  258.                 case inMenuBar:                /* process a mouse menu command (if any) */
  259.                     AdjustMenus();
  260.                     DoMenuCommand(MenuSelect(event->where));
  261.                     break;
  262.                 case inSysWindow:            /* let the system handle the mouseDown */
  263.                     SystemClick(event, window);
  264.                     break;
  265.                 case inContent:
  266.                     if ( window != FrontWindow() ) {
  267.                         SelectWindow(window);
  268.                         /*DoEvent(event);*/    /* use this line for "do first click" */
  269.                     } else
  270.                         DoContentClick(window);
  271.                     break;
  272.                 case inDrag:                /* pass screenBits.bounds to get all gDevices */
  273.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  274.                     break;
  275.                 case inGrow:
  276.                     break;
  277.                 case inZoomIn:
  278.                 case inZoomOut:
  279.                     hit = TrackBox(window, event->where, part);
  280.                     if ( hit ) {
  281.                         SetPort(window);                /* the window must be the current port... */
  282.                         EraseRect(&window->portRect);    /* because of a bug in ZoomWindow */
  283.                         ZoomWindow(window, part, true);    /* note that we invalidate and erase... */
  284.                         InvalRect(&window->portRect);    /* to make things look better on-screen */
  285.                     }
  286.                     break;
  287.             }
  288.             break;
  289.         case keyDown:
  290.         case autoKey:                        /* check for menukey equivalents */
  291.             key = event->message & charCodeMask;
  292.             if ( event->modifiers & cmdKey )            /* Command key down */
  293.                 if ( event->what == keyDown ) {
  294.                     AdjustMenus();                        /* enable/disable/check menu items properly */
  295.                     DoMenuCommand(MenuKey(key));
  296.                 }
  297.             break;
  298.         case activateEvt:
  299.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  300.             break;
  301.         case updateEvt:
  302.             DoUpdate((WindowPtr) event->message);
  303.             break;
  304.         /*    1.01 - It is not a bad idea to at least call DIBadMount in response
  305.             to a diskEvt, so that the user can format a floppy. */
  306.         case diskEvt:
  307.             if ( HiWord(event->message) != noErr ) {
  308.                 SetPt(&aPoint, kDILeft, kDITop);
  309.                 err = DIBadMount(aPoint, event->message);
  310.             }
  311.             break;
  312.         case kOSEvent:
  313.         /*    1.02 - must BitAND with 0x0FF to get only low byte */
  314.             switch ((event->message >> 24) & 0x0FF) {        /* high byte of message */
  315.                 case kSuspendResumeMessage:        /* suspend/resume is also an activate/deactivate */
  316.                     gInBackground = (event->message & kResumeMask) == 0;
  317.                     DoActivate(FrontWindow(), !gInBackground);
  318.                     break;
  319.             }
  320.             break;
  321.     }
  322. } /*DoEvent*/
  323.  
  324.  
  325.  
  326. /********************************************************************************
  327. *    Procedure:    WindowType(WindowPtr theWindowPtr)
  328. *    Purpose:    Returns our window type
  329. *    Passed:        theWindowPtr:    a pointer to the window we want to check.
  330. *    Returns:    Integer indicating the window type.
  331. ********************************************************************************/
  332. pascal    short        WindowType(WindowPtr theWindowPtr)
  333. {
  334.     short        result = kUNKNOWNWINDOW;
  335.     
  336.     
  337.     if (theWindowPtr == nil) {
  338.         result = kNILWINDOW;
  339.     } else {
  340.         if (((WindowPeek)theWindowPtr)->windowKind < 0) {
  341.             result = kDAWINDOW;
  342.         } else {
  343.             if (((AppWindowPtr)theWindowPtr)->fWindowType == kAPPWINDOW) {
  344.                 result = kAPPWINDOW;
  345.             } else {
  346.                 result = kDEBUGWINDOW;
  347.             }
  348.         }
  349.     }
  350.     
  351.     return (result);
  352. } /*WindowType*/
  353.  
  354.  
  355. /*    Change the cursor's shape, depending on its position. This also calculates the region
  356.     where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  357.     that region, an event would be generated, causing this routine to be called,
  358.     allowing us to change the region to the region the mouse is currently in. If
  359.     there is more to the event than just “the mouse moved”, we get called before the
  360.     event is processed to make sure the cursor is the right one. In any (ahem) event,
  361.     this is called again before we     fall back into WNE. */
  362.  
  363. #pragma segment Main
  364. void AdjustCursor(mouse,region)
  365.     Point        mouse;
  366.     RgnHandle    region;
  367. {
  368.     WindowPtr    window;
  369.     RgnHandle    arrowRgn;
  370.     RgnHandle    plusRgn;
  371.     Rect        globalPortRect;
  372.  
  373.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  374.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  375.         /* calculate regions for different cursor shapes */
  376.         arrowRgn = NewRgn();
  377.         plusRgn = NewRgn();
  378.  
  379.         /* start with a big, big rectangular region */
  380.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  381.  
  382.         /* calculate plusRgn */
  383.         if ( IsAppWindow(window) ) {
  384.             SetPort(window);    /* make a global version of the viewRect */
  385.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  386.             globalPortRect = window->portRect;
  387.             RectRgn(plusRgn, &globalPortRect);
  388.             SectRgn(plusRgn, window->visRgn, plusRgn);
  389.             SetOrigin(0, 0);
  390.         }
  391.  
  392.         /* subtract other regions from arrowRgn */
  393.         DiffRgn(arrowRgn, plusRgn, arrowRgn);
  394.  
  395.         /* change the cursor and the region parameter */
  396.         if ( PtInRgn(mouse, plusRgn) ) {
  397.             SetCursor(*GetCursor(plusCursor));
  398.             CopyRgn(plusRgn, region);
  399.         } else {
  400.             SetCursor(&qd.arrow);
  401.             CopyRgn(arrowRgn, region);
  402.         }
  403.  
  404.         /* get rid of our local regions */
  405.         DisposeRgn(arrowRgn);
  406.         DisposeRgn(plusRgn);
  407.     }
  408. } /*AdjustCursor*/
  409.  
  410.  
  411. /*    Get the global coordinates of the mouse. When you call OSEventAvail
  412.     it will return either a pending event or a null event. In either case,
  413.     the where field of the event record will contain the current position
  414.     of the mouse in global coordinates and the modifiers field will reflect
  415.     the current state of the modifiers. Another way to get the global
  416.     coordinates is to call GetMouse and LocalToGlobal, but that requires
  417.     being sure that thePort is set to a valid port. */
  418.  
  419. #pragma segment Main
  420. void GetGlobalMouse(mouse)
  421.     Point    *mouse;
  422. {
  423.     EventRecord    event;
  424.     
  425.     OSEventAvail(kNoEvents, &event);    /* we aren't interested in any events */
  426.     *mouse = event.where;                /* just the mouse position */
  427. } /*GetGlobalMouse*/
  428.  
  429.  
  430. /*    This is called when an update event is received for a window.
  431.     It calls DrawWindow to draw the contents of an application window.
  432.     As an effeciency measure that does not have to be followed, it
  433.     calls the drawing routine only if the visRgn is non-empty. This
  434.     will handle situations where calculations for drawing or drawing
  435.     itself is very time-consuming. */
  436.  
  437. #pragma segment Main
  438. void DoUpdate(window)
  439.     WindowPtr    window;
  440. {
  441.     if ( IsAppWindow(window) ) {
  442.         BeginUpdate(window);                /* this sets up the visRgn */
  443.         if ( ! EmptyRgn(window->visRgn) )    /* draw if updating needs to be done */
  444.             DrawWindow(window);
  445.         EndUpdate(window);
  446.     }
  447. } /*DoUpdate*/
  448.  
  449.  
  450. /*    This is called when a window is activated or deactivated.
  451.     In Sample, the Window Manager's handling of activate and
  452.     deactivate events is sufficient. Other applications may have
  453.     TextEdit records, controls, lists, etc., to activate/deactivate. */
  454.  
  455. #pragma segment Main
  456. void DoActivate(WindowPtr window, Boolean becomingActive)
  457. {
  458.     if ( IsAppWindow(window) ) {
  459.         if ( becomingActive )
  460.             /* do whatever you need to at activation */ ;
  461.         else
  462.             /* do whatever you need to at deactivation */ ;
  463.     }
  464. } /*DoActivate*/
  465.  
  466.  
  467. /*    This is called when a mouse-down event occurs in the content of a window.
  468.     Other applications might want to call FindControl, TEClick, etc., to
  469.     further process the click. */
  470.  
  471. #pragma segment Main
  472. void DoContentClick(window)
  473.     WindowPtr    window;
  474. {
  475.     SetLight(window, ! gStopped);
  476. } /*DoContentClick*/
  477.  
  478.  
  479. /* Draw the contents of the application window. We do some drawing in color, using
  480.    Classic QuickDraw's color capabilities. This will be black and white on old
  481.    machines, but color on color machines. At this point, the window’s visRgn
  482.    is set to allow drawing only where it needs to be done. */
  483.  
  484. #pragma segment Main
  485. void DrawWindow(window)
  486.     WindowPtr    window;
  487. {
  488.     SetPort(window);
  489.  
  490.     EraseRect(&window->portRect);    /* clear out any garbage that may linger */
  491.     if ( gStopped )                    /* draw a red (or white) stop light */
  492.         ForeColor(redColor);
  493.     else
  494.         ForeColor(whiteColor);
  495.     PaintOval(&gStopRect);
  496.     ForeColor(blackColor);
  497.     FrameOval(&gStopRect);
  498.     if ( ! gStopped )                /* draw a green (or white) go light */
  499.         ForeColor(greenColor);
  500.     else
  501.         ForeColor(whiteColor);
  502.     PaintOval(&gGoRect);
  503.     ForeColor(blackColor);
  504.     FrameOval(&gGoRect);
  505. } /*DrawWindow*/
  506.  
  507.  
  508. /*    Enable and disable menus based on the current state.
  509.     The user can only select enabled menu items. We set up all the menu items
  510.     before calling MenuSelect or MenuKey, since these are the only times that
  511.     a menu item can be selected. Note that MenuSelect is also the only time
  512.     the user will see menu items. This approach to deciding what enable/
  513.     disable state a menu item has the advantage of concentrating all
  514.     the decision-making in one routine, as opposed to being spread throughout
  515.     the application. Other application designs may take a different approach
  516.     that is just as valid. */
  517.  
  518. #pragma segment Main
  519. void AdjustMenus()
  520. {
  521.     WindowPtr    window;
  522.     MenuHandle    menu;
  523.  
  524.     window = FrontWindow();
  525.  
  526.     menu = GetMHandle(mFile);
  527.     if ( IsDAWindow(window) )        /* we can allow desk accessories to be closed from the menu */
  528.         EnableItem(menu, iClose);
  529.     else
  530.         DisableItem(menu, iClose);    /* but not our traffic light window */
  531.  
  532.     menu = GetMHandle(mEdit);
  533.     if ( IsDAWindow(window) ) {        /* a desk accessory might need the edit menu… */
  534.         EnableItem(menu, iUndo);
  535.         EnableItem(menu, iCut);
  536.         EnableItem(menu, iCopy);
  537.         EnableItem(menu, iClear);
  538.         EnableItem(menu, iPaste);
  539.     } else {                        /* …but we don’t use it */
  540.         DisableItem(menu, iUndo);
  541.         DisableItem(menu, iCut);
  542.         DisableItem(menu, iCopy);
  543.         DisableItem(menu, iClear);
  544.         DisableItem(menu, iPaste);
  545.     }
  546.  
  547.     menu = GetMHandle(mLight);
  548.         //the WindowType routine is used here instead of IsAppWindow because it also
  549.         //    tells us if there's a debug window present.
  550.     if (kAPPWINDOW == WindowType(window)) {    /* we know that it must be the traffic light */
  551.         EnableItem(menu, iStop);
  552.         EnableItem(menu, iGo);
  553.     } else {
  554.         DisableItem(menu, iStop);
  555.         DisableItem(menu, iGo);
  556.     }
  557.     CheckItem(menu, iStop, gStopped); /* we can also determine check/uncheck state, too */
  558.     CheckItem(menu, iGo, ! gStopped);
  559.     
  560.     if (kDEBUGWINDOW == WindowType(window)) {
  561.         EnableItem(menu, iFill);
  562.     } else {
  563.         DisableItem(menu, iFill);
  564.     }
  565. } /*AdjustMenus*/
  566.  
  567.  
  568. /*    This is called when an item is chosen from the menu bar (after calling
  569.     MenuSelect or MenuKey). It performs the right operation for each command.
  570.     It is good to have both the result of MenuSelect and MenuKey go to
  571.     one routine like this to keep everything organized. */
  572.  
  573. #pragma segment Main
  574. void DoMenuCommand(menuResult)
  575.     long        menuResult;
  576. {
  577.     short        menuID;                /* the resource ID of the selected menu */
  578.     short        menuItem;            /* the item number of the selected menu */
  579.     short        itemHit;
  580.     Str255        daName;
  581.     short        daRefNum;
  582.     Boolean        handledByDA;
  583.  
  584.     menuID = HiWord(menuResult);    /* use macros for efficiency to... */
  585.     menuItem = LoWord(menuResult);    /* get menu item number and menu number */
  586.     switch ( menuID ) {
  587.         case mApple:
  588.             switch ( menuItem ) {
  589.                 case iAbout:        /* bring up alert for About */
  590.                     itemHit = Alert(rAboutAlert, nil);
  591.                     break;
  592.                 default:            /* all non-About items in this menu are DAs */
  593.                     /* type Str255 is an array in MPW 3 */
  594.                     GetItem(GetMHandle(mApple), menuItem, daName);
  595.                     daRefNum = OpenDeskAcc(daName);
  596.                     break;
  597.             }
  598.             break;
  599.         case mFile:
  600.             switch ( menuItem ) {
  601.                 case iClose:
  602.                     DoCloseWindow(FrontWindow());
  603.                     break;
  604.                 case iQuit:
  605.                     Terminate();
  606.                     break;
  607.             }
  608.             break;
  609.         case mEdit:                    /* call SystemEdit for DA editing & MultiFinder */
  610.             handledByDA = SystemEdit(menuItem-1);    /* since we don’t do any Editing */
  611.             break;
  612.         case mLight:
  613.             switch ( menuItem ) {
  614.                 case iStop:
  615.                     SetLight(FrontWindow(), true);
  616.                     break;
  617.                 case iGo:
  618.                     SetLight(FrontWindow(), false);
  619.                     break;
  620.                 
  621.                 case iFill:
  622.                     FillTermWindow(gTermWindowPtr);
  623.                     break;
  624.             }
  625.             break;
  626.     }
  627.     HiliteMenu(0);                    /* unhighlight what MenuSelect (or MenuKey) hilited */
  628. } /*DoMenuCommand*/
  629.  
  630.  
  631. /* Change the setting of the light. */
  632.  
  633. #pragma segment Main
  634. void SetLight( WindowPtr window, Boolean newStopped )
  635. {
  636.     if ( newStopped != gStopped ) {
  637.         gStopped = newStopped;
  638.         SetPort(window);
  639.         InvalRect(&window->portRect);
  640.     }
  641.  
  642. //*****************************************************
  643. //    Code added for TermWindow
  644. //*****************************************************
  645.     {
  646.         char    str[255];
  647.         long     dataLen;
  648.  
  649.         if(gStopped)
  650.             sprintf(str, "Red Light.\n\r");
  651.         else
  652.             sprintf(str, "Green Light.\n\r");
  653.             
  654.         dataLen = strlen(str);
  655.         WriteToTermWindow(gTermWindowPtr, str, &dataLen);
  656.     }
  657. } /*SetLight*/
  658.  
  659.  
  660. /* Close a window. This handles desk accessory and application windows. */
  661.  
  662. /*    1.01 - At this point, if there was a document associated with a
  663.     window, you could do any document saving processing if it is 'dirty'.
  664.     DoCloseWindow would return true if the window actually closed, i.e.,
  665.     the user didn’t cancel from a save dialog. This result is handy when
  666.     the user quits an application, but then cancels the save of a document
  667.     associated with a window. */
  668.  
  669. #pragma segment Main
  670. Boolean DoCloseWindow(WindowPtr window)
  671. {
  672.     if ( IsDAWindow(window) )
  673.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  674.     else if ( IsAppWindow(window) )
  675.         CloseWindow(window);
  676.     return true;
  677. } /*DoCloseWindow*/
  678.  
  679.  
  680. /**************************************************************************************
  681. *** 1.01 DoCloseBehind(window) was removed ***
  682.  
  683.     1.01 - DoCloseBehind was a good idea for closing windows when quitting
  684.     and not having to worry about updating the windows, but it suffered
  685.     from a fatal flaw. If a desk accessory owned two windows, it would
  686.     close both those windows when CloseDeskAcc was called. When DoCloseBehind
  687.     got around to calling DoCloseWindow for that other window that was already
  688.     closed, things would go very poorly. Another option would be to have a
  689.     procedure, GetRearWindow, that would go through the window list and return
  690.     the last window. Instead, we decided to present the standard approach
  691.     of getting and closing FrontWindow until FrontWindow returns NIL. This
  692.     has a potential benefit in that the window whose document needs to be saved
  693.     may be visible since it is the front window, therefore decreasing the
  694.     chance of user confusion. For aesthetic reasons, the windows in the
  695.     application should be checked for updates periodically and have the
  696.     updates serviced.
  697. **************************************************************************************/
  698.  
  699.  
  700. /* Clean up the application and exit. We close all of the windows so that
  701.  they can update their documents, if any. */
  702.  
  703. /*    1.01 - If we find out that a cancel has occurred, we won't exit to the
  704.     shell, but will return instead. */
  705.  
  706. #pragma segment Main
  707. void Terminate()
  708. {
  709.     WindowPtr    aWindow;
  710.     Boolean        closed;
  711.     
  712.         //added to keep TermWindow handling simple
  713.     ExitToShell();
  714.     
  715.     closed = true;
  716.     do {
  717.         aWindow = FrontWindow();                /* get the current front window */
  718.         if (aWindow != nil)
  719.             closed = DoCloseWindow(aWindow);    /* close this window */    
  720.     }
  721.     while (closed && (aWindow != nil));
  722.     if (closed)
  723.         ExitToShell();                            /* exit if no cancellation */
  724. } /*Terminate*/
  725.  
  726.  
  727. /*    Set up the whole world, including global variables, Toolbox managers,
  728.     and menus. We also create our one application window at this time.
  729.     Since window storage is non-relocateable, how and when to allocate space
  730.     for windows is very important so that heap fragmentation does not occur.
  731.     Because Sample has only one window and it is only disposed when the application
  732.     quits, we will allocate its space here, before anything that might be a locked
  733.     relocatable object gets into the heap. This way, we can force the storage to be
  734.     in the lowest memory available in the heap. Window storage can differ widely
  735.     amongst applications depending on how many windows are created and disposed. */
  736.  
  737. /*    1.01 - The code that used to be part of ForceEnvirons has been moved into
  738.     this module. If an error is detected, instead of merely doing an ExitToShell,
  739.     which leaves the user without much to go on, we call AlertUser, which puts
  740.     up a simple alert that just says an error occurred and then calls ExitToShell.
  741.     Since there is no other cleanup needed at this point if an error is detected,
  742.     this form of error- handling is acceptable. If more sophisticated error recovery
  743.     is needed, an exception mechanism, such as is provided by Signals, can be used. */
  744.  
  745. #pragma segment Initialize
  746. void Initialize()
  747. {
  748.     Handle        menuBar;
  749.     AppWindowPtr    appWindow = nil;
  750.     WindowPtr    window;
  751.     long        total, contig;
  752.     EventRecord event;
  753.     short        count;
  754.     
  755.     OSErr                result = noErr;        //added these variables because of TermWindow
  756.     Rect                windowRect = { 0, 0, 0, 0 };
  757.     WindowPtr            aWindowPtr = nil;
  758.     
  759.     Str255                tempString;            //display MemError() if not enough memory.
  760.  
  761.  
  762.     gInBackground = false;
  763.  
  764.     InitGraf((Ptr) &qd.thePort);
  765.     InitFonts();
  766.     InitWindows();
  767.     InitMenus();
  768.     TEInit();
  769.     InitDialogs(nil);
  770.     InitCursor();
  771.     
  772.     /*    Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  773.          if you are using it. */
  774.     /*    NOTE -- It is no longer necessary, and actually unhealthy, to check
  775.         PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  776.         of checking for port availability themselves. */
  777.     
  778.     /*    This next bit of code is necessary to allow the default button of our
  779.         alert be outlined.
  780.         1.02 - Changed to call EventAvail so that we don't lose some important
  781.         events. */
  782.      
  783.     for (count = 1; count <= 3; count++)
  784.         EventAvail(everyEvent, &event);
  785.     
  786.     /*    Ignore the error returned from SysEnvirons; even if an error occurred,
  787.         the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  788.         call to SysEnvirons by calling it after initializing AppleTalk. */
  789.      
  790.     SysEnvirons(kSysEnvironsVersion, &gMac);
  791.     
  792.     /* Make sure that the machine has at least 128K ROMs. If it doesn't, exit. */
  793.     
  794.     if (gMac.machineType < 0) AlertUser();
  795.     
  796.     /*    1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  797.         in TrapAvailable if a tool trap value is out of range. */
  798.         
  799.     gHasWaitNextEvent = TrapAvailable(_WaitNextEvent, ToolTrap);
  800.  
  801.     /*    1.01 - We used to make a check for memory at this point by examining ApplLimit,
  802.         ApplicZone, and StackSpace and comparing that to the minimum size we told
  803.         MultiFinder we needed. This did not work well because it assumed too much about
  804.         the relationship between what we asked MultiFinder for and what we would actually
  805.         get back, as well as how to measure it. Instead, we will use an alternate
  806.         method comprised of two steps. */
  807.      
  808.     /*    It is better to first check the size of the application heap against a value
  809.         that you have determined is the smallest heap the application can reasonably
  810.         work in. This number should be derived by examining the size of the heap that
  811.         is actually provided by MultiFinder when the minimum size requested is used.
  812.         The derivation of the minimum size requested from MultiFinder is described
  813.         in Sample.h. The check should be made because the preferred size can end up
  814.         being set smaller than the minimum size by the user. This extra check acts to
  815.         insure that your application is starting from a solid memory foundation. */
  816.      
  817.     if ((long) GetApplLimit() - (long) ApplicZone() < kMinHeap) AlertUser();
  818.     
  819.     /*    Next, make sure that enough memory is free for your application to run. It
  820.         is possible for a situation to arise where the heap may have been of required
  821.         size, but a large scrap was loaded which left too little memory. To check for
  822.         this, call PurgeSpace and compare the result with a value that you have determined
  823.         is the minimum amount of free memory your application needs at initialization.
  824.         This number can be derived several different ways. One way that is fairly
  825.         straightforward is to run the application in the minimum size configuration
  826.         as described previously. Call PurgeSpace at initialization and examine the value
  827.         returned. However, you should make sure that this result is not being modified
  828.         by the scrap's presence. You can do that by calling ZeroScrap before calling
  829.         PurgeSpace. Make sure to remove that call before shipping, though. */
  830.     
  831.     /* ZeroScrap(); */
  832.  
  833.     PurgeSpace(&total, &contig);
  834.     if (total < kMinSpace) AlertUser();
  835.  
  836.     /*    The extra benefit to waiting until after the Toolbox Managers have been initialized
  837.         to check memory is that we can now give the user an alert to tell him/her what
  838.         happened. Although it is possible that the memory situation could be worsened by
  839.         displaying an alert, MultiFinder would gracefully exit the application with
  840.         an informative alert if memory became critical. Here we are acting more
  841.         in a preventative manner to avoid future disaster from low-memory problems. */
  842.  
  843.     /*     we will allocate our own window storage instead of letting the Window
  844.         Manager do it because GetNewWindow may load in temp. resources before
  845.         making the NewPtr call, and this can lead to heap fragmentation. */
  846.     appWindow = (AppWindowPtr) NewPtrClear(sizeof(AppWindowRec));
  847.     if (nil == appWindow) {
  848.         DebugStr("\p no appWindow");
  849.         NumToString(MemError(), tempString);
  850.         DebugStr(tempString);
  851.         AlertUser();
  852.     }
  853.     appWindow->fWindowType = kAPPWINDOW;
  854.     window = GetNewWindow(rWindow, (Ptr)appWindow, (WindowPtr) -1);
  855.     if (nil == window) {
  856.         DebugStr("\p no window");
  857.         NumToString(MemError(), tempString);
  858.         DebugStr(tempString);
  859.         AlertUser();
  860.     }
  861.  
  862.     menuBar = GetNewMBar(rMenuBar);            /* read menus into menu bar */
  863.     if ( menuBar == nil ) AlertUser();
  864.     SetMenuBar(menuBar);                    /* install menus */
  865.     DisposHandle(menuBar);
  866.     AddResMenu(GetMHandle(mApple), 'DRVR');    /* add DA names to Apple menu */
  867.     DrawMenuBar();
  868.     
  869.     gStopped = true;
  870.     if ( !GoGetRect(rStopRect, &gStopRect) )
  871.         AlertUser();                        /* the stop light rectangle */
  872.     if ( !GoGetRect(rGoRect, &gGoRect) )
  873.         AlertUser();                        /* the go light rectangle */
  874.  
  875.  
  876. //*****************************************************
  877. //    Code added for TermWindow
  878. //*****************************************************
  879.     
  880.     if (noErr == (result = InitTermMgr())) {
  881.         windowRect.left = 170;
  882.         windowRect.top = 60;
  883.         windowRect.right = windowRect.left + 350;
  884.         windowRect.bottom = 290;
  885.         
  886.         if (nil != (gTermWindowPtr = (TermWindowPtr)NewPtrClear(sizeof(TermWindowRec)))) {
  887.             if (noErr == (result = NewTermWindow(&gTermWindowPtr,
  888.                                     &windowRect, 
  889.                                     "\pA sample terminal window", 
  890.                                     true,
  891.                                     zoomDocProc, 
  892.                                     nil,
  893.                                     false, 
  894.                                     "\pVT102 Tool"))) {
  895.                 //we initialized!
  896.             } else {
  897.                 DebugStr("\p Error @NewTermWindow");
  898.                 AlertUser();                        // error at NewTermWindow
  899.             }
  900.         } else {
  901.             DebugStr("\p Error @NewPtr;dw ResErr;dw MemErr");
  902.             AlertUser();                        // error at NewPtr
  903.         }
  904.     } else {
  905.         AlertUser();                        // error at InitTermMgr
  906.     }
  907. } /*Initialize*/
  908.  
  909.  
  910. /*    This utility loads the global rectangles that are used by the window
  911.     drawing routines. It shows how the resource manager can be used to hold
  912.     values in a convenient manner. These values are then easily altered without
  913.     having to re-compile the source code. In this particular case, we know
  914.     that this routine is being called at initialization time. Therefore,
  915.     if a failure occurs here, we will assume that the application is in such
  916.     bad shape that we should just exit. Your error handling may differ, but
  917.     the check should still be made. */
  918.     
  919. #pragma segment Initialize
  920. Boolean GoGetRect(short rectID,Rect *theRect)
  921. {
  922.     Handle        resource;
  923.     
  924.     resource = GetResource('RECT', rectID);
  925.     if ( resource != nil ) {
  926.         *theRect = **((Rect**) resource);
  927.         return true;
  928.     }
  929.     else
  930.         return false;
  931. } /* GoGetRect */
  932.  
  933.  
  934.  
  935. /********************************************************************************
  936.     Procedure:    IsAppWindow
  937.     Purpose:    Check to see if a window belongs to the application. 
  938.         If the window pointer
  939.         passed was NIL, then it could not be an application window. WindowKinds
  940.         that are negative belong to the system and windowKinds less than userKind
  941.         are reserved by Apple except for windowKinds equal to dialogKind, which
  942.         mean it is a dialog.
  943.         1.02 - In order to reduce the chance of accidentally treating some window
  944.         as an AppWindow that shouldn't be, we'll only return true if the windowkind
  945.         is userKind. If you add different kinds of windows to Sample you'll need
  946.         to change how this all works.
  947.         
  948.         CSH -- Since we have more than one window type, I've defined a structure
  949.             at the top of this file for our window storage and a short called 
  950.             a fWindowType.  The new field allows us to differentiate between
  951.             different types of application windows.
  952.     Passed:        window            windowPtr that we want to check.
  953.     Returns:    True is traffic light, false if not.
  954. ********************************************************************************/
  955. #pragma segment Main
  956. Boolean IsAppWindow(WindowPtr window)
  957. {
  958.         //
  959.         //the changes here were necessary to stop the traffic light from
  960.         //    being drawn in the terminal window -- CSH
  961.         //
  962.     short        wType;
  963.     Boolean        result = false;
  964.     
  965.  
  966.     if (kAPPWINDOW == (wType = WindowType(window))) {
  967.         result = true;
  968.     } else {
  969.         result = false;
  970.     }
  971.     
  972.     return (result);
  973. } /*IsAppWindow*/
  974.  
  975.  
  976.  
  977. /* Check to see if a window belongs to a desk accessory. */
  978. #pragma segment Main
  979. Boolean IsDAWindow(WindowPtr window)
  980. {
  981.     if ( window == nil )
  982.         return false;
  983.     else    /* DA windows have negative windowKinds */
  984.         return ((WindowPeek) window)->windowKind < 0;
  985. } /*IsDAWindow*/
  986.  
  987.  
  988. /*    Check to see if a given trap is implemented. This is only used by the
  989.     Initialize routine in this program, so we put it in the Initialize segment.
  990.     The recommended approach to see if a trap is implemented is to see if
  991.     the address of the trap routine is the same as the address of the
  992.     Unimplemented trap. */
  993. /*    1.02 - Needs to be called after call to SysEnvirons so that it can check
  994.     if a ToolTrap is out of range of a pre-MacII ROM. */
  995.  
  996. #pragma segment Initialize
  997. Boolean TrapAvailable(short tNumber,TrapType tType)
  998. {
  999.     if ( ( tType == ToolTrap ) &&
  1000.         ( gMac.machineType > envMachUnknown ) &&
  1001.         ( gMac.machineType < envMacII ) ) {        /* it's a 512KE, Plus, or SE */
  1002.         tNumber = tNumber & 0x03FF;
  1003.         if ( tNumber > 0x01FF )                    /* which means the tool traps */
  1004.             tNumber = _Unimplemented;            /* only go to 0x01FF */
  1005.     }
  1006.     return NGetTrapAddress(tNumber, tType) != GetTrapAddress(_Unimplemented);
  1007. } /*TrapAvailable*/
  1008.  
  1009.  
  1010. /*    Display an alert that tells the user an error occurred, then exit the program.
  1011.     This routine is used as an ultimate bail-out for serious errors that prohibit
  1012.     the continuation of the application. Errors that do not require the termination
  1013.     of the application should be handled in a different manner. Error checking and
  1014.     reporting has a place even in the simplest application. The error number is used
  1015.     to index an 'STR#' resource so that a relevant message can be displayed. */
  1016.  
  1017. #pragma segment Main
  1018. void AlertUser()
  1019. {
  1020.     short        itemHit;
  1021.  
  1022.     SetCursor(&qd.arrow);
  1023.     itemHit = Alert(rUserAlert, nil);
  1024.     ExitToShell();
  1025. } /* AlertUser */